package com.crape.common.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class FileUtils {

    public static void writeFile(String filePath, String fileName, String fileContent) {
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdir();
            }
            FileWriter theFile = new FileWriter(filePath + fileName, false);
            PrintWriter out = new PrintWriter(theFile);
            out.println(fileContent);
            out.close();
            theFile.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void changeFileCode(String filePath, String orCode, String newCode) {
        try {
            FileInputStream fi = new FileInputStream(filePath);
            int length = fi.available();
            FileChannel fc = fi.getChannel();
            ByteBuffer buff = ByteBuffer.allocate(length);
            fc.read(buff);
            buff.flip();
            fc.close();
            fi.close();

            buff.rewind();
            Charset decoder = Charset.forName(orCode);
            Charset encoder = Charset.forName(newCode);

            CharBuffer cb = decoder.decode(buff);
            ByteBuffer buff2 = encoder.encode(cb);

            FileOutputStream fo = new FileOutputStream(filePath);
            fc = fo.getChannel();

            fc.write(buff2);
            fc.close();
            fo.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void readFile(String filePath, ArrayList<String> list) throws Exception {
        File rf = null;
        InputStreamReader read = null;
        BufferedReader reader = null;
        try {
            rf = new File(filePath);
            read = new InputStreamReader(new FileInputStream(rf), "UTF-8");
            reader = new BufferedReader(read);
            String line = null;
            while ((line = reader.readLine()) != null) {
                list.add(line);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (null != reader) {
                reader.close();
            }
            if (null != read) {
                read.close();
            }
        }
    }
    
    public static void readFile(File rf, StringBuilder str) throws Exception {
        if (rf == null || str == null) {
            str = new StringBuilder();
            return;
        }
        InputStreamReader read = null;
        BufferedReader reader = null;
        try {
            read = new InputStreamReader(new FileInputStream(rf), "UTF-8");
            reader = new BufferedReader(read);
            String line = null;
            while ((line = reader.readLine()) != null) {
                str.append(line);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (null != reader) {
                reader.close();
            }
            if (null != read) {
                read.close();
            }
        }
    }

    public static List<File> getFiles(String rootPath) {
        List<File> list = new ArrayList<File>();
        File file = new File(rootPath);
        File[] files = file.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (!files[i].isDirectory()) {
                list.add(files[i]);
            }
        }
        return list;
    }
    
    public static List<File> getDirectorys(String rootPath) {
        List<File> list = new ArrayList<File>();
        File file = new File(rootPath);
        File[] files = file.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                list.add(files[i]);
            }
        }
        return list;
    }
    
    public static List<String> getFileNames(List<File> files) {
        List<String> list = new ArrayList<String>();
        if (files == null) {
            return list;
        }
        for (File file : files) {
            list.add(file.getName());
        }
        return list;
    }

    public static String getWebinfPath() {
        String res = null;
        String classname = FileUtils.class.getName().replace('.', '/') + ".class";
        ClassLoader cl = FileUtils.class.getClassLoader();
        if (cl != null) {
            java.net.URL url = cl.getResource(classname);
            if (url != null) {
                String path = url.getFile();
                int fileStrPosition = path.indexOf("file:/");
                int begin = 0;
                int end = path.indexOf("classes/" + classname);
                if (fileStrPosition >= 0) begin = fileStrPosition + 5;

                if (end < 0) {

                    end = path.indexOf("lib/");
                    if (end < 0) {

                        int tmpend = path.indexOf("!/");
                        end = path.substring(0, tmpend).lastIndexOf("/");
                    }
                }
                String rf = path.substring(begin, end);
                res = new File(rf).getAbsolutePath().replace('\\', '/') + "/";
            }
        }
        try {
            res = java.net.URLDecoder.decode(res, "UTF-8");
        } catch (UnsupportedEncodingException ex) {
        }
        return res;
    }

    @SuppressWarnings("rawtypes")
	public static String getClassesPath(Class c) {
        String res = null;
        String classname = c.getName().replace('.', '/') + ".class";
        ClassLoader cl = c.getClassLoader();
        if (cl != null) {
            java.net.URL url = cl.getResource(classname);
            if (url != null) {
                String path = url.getFile();
                int fileStrPosition = path.indexOf("file:/");
                int begin = 0;
                int end = path.length();
                if (fileStrPosition >= 0) begin = fileStrPosition + 5;

                end = path.indexOf(classname);
                if (end < 0) {
                    end = path.length();
                }
                String rf = path.substring(begin, end);
                res = new File(rf).getAbsolutePath().replace('\\', '/') + "/";
            }
        }
        try {
            if (null != res) {
                res = java.net.URLDecoder.decode(res, "UTF-8");
            }
        } catch (UnsupportedEncodingException ex) {
        }
        return res;
    }

    public static void main(String[] argz) {
        getWebinfPath();
    }
}
